package com.corpgovernment.organization.service;


import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.corpgovernment.organization.event.OrgInitEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.corpgovernment.common.enums.PayTypeEnum;
import com.corpgovernment.common.enums.SiteEnum;
import com.corpgovernment.organization.dataloader.db.MbOrgInfoLoader;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.entity.db.MbOrgPayType;
import com.corpgovernment.organization.enumm.CorpPayTypeEnum;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;

import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author zl.cui
 * @date 2023/8/22
 */
@Service
@Slf4j
public class SyncPayConfigService {
    @Autowired
    private IOrgPayTypeService orgPayTypeService;
    @Autowired
    private MbOrgInfoLoader mbOrgInfoLoader;

    public void importOrganizationConfig(List<OrgInitEvent.PayTypeConfigType>  payTypeConfigList) {
        log.warn("支付设置:{}", JsonUtils.toJsonString(payTypeConfigList));
        if (CollectionUtils.isEmpty(payTypeConfigList)){
            return;
        }
        payTypeConfigList.stream()
            .forEach(payType -> {
                List<MbOrgInfo> mbOrgInfoList = mbOrgInfoLoader.selectByBusinessCode(payType.getBusinessCode());
                if (CollectionUtils.isEmpty(mbOrgInfoList)) {
                    log.warn("根据businessCode：{}未找到", payType.getBusinessCode());
                    return;
                }
                for (SiteEnum siteEnum : SiteEnum.values()) {
                    if (siteEnum == SiteEnum.OTHER || siteEnum == SiteEnum.AIRPORTTRANSFER || siteEnum == SiteEnum.TRAINTRANSFER) {
                        continue;
                    }
                    try {
                        Field payTypeField = OrgInitEvent.PayTypeConfigType.class.getDeclaredField(siteEnum.getCode());
                        payTypeField.setAccessible(true);
                        String payTypeDesc = (String)payTypeField.get(payType);
                        String[] splitDesc = null;
                        if (StringUtils.isNotBlank(payTypeDesc)){
                            splitDesc = payTypeDesc.split("，");
                        } else {
                            splitDesc = new String[]{PayTypeEnum.ACCNT.getName(), PayTypeEnum.PPAY.getName()};
                        }
                        List<String> payTypeDescList = Stream.of(splitDesc).map(desc -> {
                            if (PayTypeEnum.PPAY.getName().equals(desc)) {
                                return PayTypeEnum.PPAY.getType();
                            } else {
                                return PayTypeEnum.ACCNT.getType();
                            }
                        }).collect(Collectors.toList());
                        log.info("payTypeDescList:{}", JsonUtils.toJsonString(payTypeDescList));
                        addOrUpdatePayType(mbOrgInfoList.get(0).getOrgId(), payTypeDescList, siteEnum.getCode());
                    } catch (Exception e) {
                        log.error("导入失败：", e);
                    }
                }
            });
    }

    private void addOrUpdatePayType(String orgId, List<String> payTypeList, String productLine){
        if (CollectionUtils.isEmpty(payTypeList)){
            return;
        }

        List<MbOrgPayType> mbOrgPayTypeList = orgPayTypeService.findByOrgId(orgId, productLine);
        // 该产线原来有支付方式
        if (CollectionUtils.isNotEmpty(mbOrgPayTypeList)){
            // 有因公因私两种支付方式
            Map<String, List<MbOrgPayType>> map = mbOrgPayTypeList.stream().collect(Collectors.groupingBy(MbOrgPayType::getCorpPayType));
            // 处理因公的支付方式
            Stream.of(PayTypeEnum.values()).forEach(payType -> {
                // 支付类型（因公因私）->支付方式（ACCNT公司支付 PPAY个人支付）
                List<MbOrgPayType> mapPayTypeList = map.get(payType.getType());
                // 原来没有数据，则保存
                if (CollectionUtils.isEmpty(mapPayTypeList) && payTypeList.contains(payType.getType())){
                    orgPayTypeService.save(new MbOrgPayType(orgId, CorpPayTypeEnum.PUB.toString(), payType.getType(), productLine));
                }
                // 如果的表里没有的支付方式->删除
                if (CollectionUtils.isNotEmpty(mapPayTypeList) && !payTypeList.contains(payType.getType())){
                    orgPayTypeService.deletePayType(orgId, CorpPayTypeEnum.PUB.toString(), payType.getType(), productLine);
                }
            });
            // 处理因私的支付方式
            List<MbOrgPayType> ownPersonalPayTypeList = mbOrgPayTypeList.stream()
                    .filter(t -> CorpPayTypeEnum.OWN.toString().equals(t.getCorpPayType()) && PayTypeEnum.PPAY.getType().equals(t.getPaytype()))
                    .collect(Collectors.toList());
            // 如果原来没有因私个人支付，则加入
            if (CollectionUtils.isEmpty(ownPersonalPayTypeList)){
                orgPayTypeService.save(new MbOrgPayType(orgId, CorpPayTypeEnum.OWN.toString(), PayTypeEnum.PPAY.getType(), productLine));
            }
        // 该产线原来没有支付方式
        } else {
            // 因公的由导入的决定
            payTypeList.forEach(payType -> {
                orgPayTypeService.save(new MbOrgPayType(orgId, CorpPayTypeEnum.PUB.toString(), payType, productLine));
            });
            // 因私的直接设置个人支付
            orgPayTypeService.save(new MbOrgPayType(orgId, CorpPayTypeEnum.OWN.toString(), PayTypeEnum.PPAY.getType(), productLine));
        }



    }
}
